from flask import g

from info.models import User, News, Category
from info.utils.commons import user_login_data
from info.utils.response_code import RET
from . import index_blue
from info import redis_store
import logging
from flask import current_app,render_template,request,session, jsonify

@index_blue.route('/newslist')
def newlist():
    page = request.args.get('page','1')
    cid = request.args.get('cid','1')
    per_page = request.args.get('per_page','5')

    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        page = 1
        per_page = 5


    try:


        condition = ""

        if cid != "1":
            condition = (News.category_id == cid)

        paginate = News.query.filter(condition).order_by(News.create_time.desc()).paginate(page, per_page,
                                                                                           False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取新闻失败")

    totalPage = paginate.pages
    items = paginate.items
    currentPage = paginate.page


    newList = []
    for news in items:
        newList.append(news.to_dict())


    return jsonify(errno=RET.OK, errmsg="获取成功", totalPage=totalPage, currentPage=currentPage, newsList=newList)


@index_blue.route('/')
@user_login_data
def show_index():

    #4测试日志使用
    # user_id = session.get('user_id')
    # user = None
    # if not user:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)

    try:
        news_list = News.query.order_by(News.clicks).limit(10).all()
    except Exception as e:
        current_app.logger.error(e)

    dict_news = []

    for news in news_list:
        dict_news.append(news.to_dict())


    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)

    category_list = []

    for category in categories:
        category_list.append(category.to_dict())

    dict_data ={
        'user_info' : g.user.to_dict() if g.user else None,
        'click_news_list' : dict_news,
        'category_list': category_list
    }

    return render_template('news/index.html' , dict_data = dict_data)

@index_blue.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')

@index_blue.route('/404')
@user_login_data
def page_not_found():
    data = {
        "user_info":g.user.to_dict() if g.user else ""
    }
    return render_template('news/404.html',dict_data=data)